const browserMap = {
  ie: "0",
  firefox: "0",
  safari: "0",
  konq: "0",
  opera: "0",
  chrome: "0",
};

export const geckoReg = /rv:(.+)\) Gecko\/([\d|.]{3,8})/;
export const appleWebkitReg = /AppleWebKit\/(\S+)/;
export const chromeReg = /Chrome\/(\S+)/;
export const safariReg = /Version\/(\S+)/;
export const firefoxReg = /Firefox\/(\S+)/;
export const ieReg = /MSIE (\S+)/;

export function detectBrowserVersion() {
  const ua = navigator.userAgent,
    b = browserMap;
  // @ts-expect-error: opera browser
  if (window.opera) {
    // @ts-expect-error: opera browser
    b.opera = window.opera.version();
  } else if (appleWebkitReg.test(ua)) {
    // 判断是 Chrome 还是 safari
    if (chromeReg.test(ua)) {
      b.chrome = chromeReg.exec(ua)![1];
    } else if (safariReg.test(ua)) {
      // 仅使用于 safari 3 及其更高版本
      b.safari = safariReg.exec(ua)![1];
    } else {
      // 个别情况-未获取到 safari 版本号的处理
    }
  } else if (/KHTML\/(\S+)/.test(ua) || /Konqueror\/([^;]+)/.test(ua)) {
    b.konq = RegExp["$1"];
  } else if (geckoReg.test(ua)) {
    if (firefoxReg.test(ua)) {
      // 火狐浏览器
      b.firefox = firefoxReg.exec(ua)![1];
    } else {
      // 其他情况
    }
  } else if (ieReg.test(ua)) {
    b.ie = ieReg.exec(ua)![1];
  }
  return b;
}

export function checkBrowser(avaliableVer: Partial<Record<keyof typeof browserMap, string | number>>) {
  if (!avaliableVer) avaliableVer = {};

  const BrowserInfo = detectBrowserVersion();
  let ver, browser;

  const keys = Object.keys(BrowserInfo);

  for (let i = 0; i < keys.length; i++) {
    const k = keys[i] as keyof typeof browserMap;
    if (
      typeof avaliableVer[k] === "string" &&
      typeof BrowserInfo[k] === "string"
    ) {
      // ver always string because typeof judge
      const targetVer = (avaliableVer[k] as string).split(".")[0],
        currentVer = BrowserInfo[k].split(".")[0];

      if (currentVer === "0") continue;
      else if (k === "ie" && currentVer !== "0")
        return [false, k, currentVer];
      ver = BrowserInfo[k];
      browser = k;
      if (parseInt(targetVer) > parseInt(currentVer))
        return [false, k, ver];
    }
  }

  return [true, browser, ver];
}

const result = checkBrowser({
  firefox: "0.0",
  ie: "12",
  chrome: "90.0",
  safari: "14.1",
  opera: "70.0",
}) ?? [false, "", ""];

const res = result[0];
const b = result[1];
const ver = result[2];

if (!res || !b || !ver) {
  if (!sessionStorage.getItem("browserVersionWarn")) {
    sessionStorage.setItem("browserVersionWarn", "true");
    const warnStr = `当前检测到您的浏览器版本过低，可能会出现页面显示以及无法交互等问题，推荐您通过PC端进行访问并使用 Chrome 或 Edge 浏览器以获得最佳体验！\n当前浏览器：${b ?? "未知"
      }\n当前浏览器版本：${ver ?? "未知"}\n如存在误报，可以加入反馈群：831277455 进行反馈`;
    alert(warnStr);
  }
}